﻿using AutoMapper;
using ERPSystem.Common.Domains.SalesOrderCommom;
using ERPSystem.Common.Domains.supplier;
using ERPSystem.Common.DTO;
using ERPSystem.Common.Infrastructure.IRepository;
using ERPSystem.Enum.CommonErrorCodes;
using MediatR;

namespace SalesManagementWrite.API.SalesManagementWrites.SalesOrders
{
    public class SalesOrderCreateHander : IRequestHandler<SalesOrderCreateCommand, Result>
    {
        private readonly IMapper _mapper;
        private readonly IBaseRepository<SalesOrder> _salesOrderRepository;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="salesOrderRepository"></param>
        public SalesOrderCreateHander(IMapper mapper, IBaseRepository<SalesOrder> salesOrderRepository)
        {
            _mapper = mapper;
            _salesOrderRepository = salesOrderRepository;
        }
        /// <summary>
        /// 销售订单新增接口
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(SalesOrderCreateCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                var salesOrder = _mapper.Map<SalesOrder>(request);
                salesOrder.CreatedOwnerId = "张三";
                salesOrder.CreatedTime = DateTime.Now;
                salesOrder.Auditor = "李四";
                salesOrder.AuditDate = DateTime.Now;
                var list = await _salesOrderRepository.Add(salesOrder);
                if (list > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Msg = "添加成功";
                }
                else
                {
                    result.Msg = "添加失败";
                }
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
